<template>
    <div class="container">
        <div class="fixed-header">
            <div class="wrong-list"><span>错题列表</span><span>（共查出<i>{{ wrongQuesSum }}</i>道题）</span></div>
        </div>
        <cus-skeleton :loading="loading">
            <div class="section">
                <div class="item" v-for="data in dataset" :key="data.id">
                    <div class="content-text">
                        <div class="title" v-html="rewriteRichPic(data.title)"></div>
                        <div v-question="data"></div>
                    </div>
                    <div class="flex-box" v-show="showAnswer">
                        <div class="label">答案</div>
                        <div class="flex-main" v-html="data.answer"></div>
                    </div>
                    <div class="flex-box" v-show="data.showAnalysis">
                        <div class="label">解析</div>
                        <div class="flex-main">
                            <span v-html="data.analysis" v-if="data.analysis"/>
                            <span v-else>暂无解析</span>
                        </div>
                    </div>
                    <div class="flex-box" v-show="data.showAnalysis">
                        <div class="label">知识点</div>
                        <div class="flex-main">
                            <span v-if="data.knowledges">{{ filterKnowle(data) }}</span>
                            <span v-else>暂无知识点</span>
                        </div>
                    </div>
                    <div class="footer">
                        <p>{{ data.questionTypeName }}</p>
                        <p>
                            <span>错误时间：</span><span>{{ data.createTime }}</span>
                        </p>
                        <p>
                            <span>难度：</span><span>{{ data.difficult }}</span>
                        </p>
                        <div>
                            <p><i @click="data.showAnalysis = !data.showAnalysis">解析</i></p>
                            <!-- <p><i @click="similarPreview(data.id)">相似题</i></p> -->
                            <a class="cart-icon" @click.prevent="addCart(data)"
                               :class="{ active: !!cartList.find((i) => i.id === data.id) }"/>
                        </div>
                    </div>
                </div>
                <template v-if="!dataset.length && !loading">
                    <cus-empty/>
                </template>
                <template v-if="dataset.length && !loading">
                    <el-pagination
                            v-model:current-page="pageAorder.current"
                            v-model:page-size="pageAorder.size"
                            :total="total"
                            @current-change="request(searchParams)"
                            layout="prev, pager, next"
                    />
                </template>
            </div>
        </cus-skeleton>
    </div>
    <TestBasketComponent :question-list="cartList"/>
</template>

<script lang="ts">
    import {ref, Ref, reactive, computed, onMounted, nextTick} from "vue";
    import {useStore} from "vuex";
    import TestBasketComponent from "@/views/question/components/test-basket.vue";
    import QuestionDirective from "@/views/utils/question.directive";
    import StudentListComponent from './student-list.vue'
    import $, {emitter} from "$";

    const difficultFilter = (v) =>
        [
            {name: "易", id: 11},
            {name: "较易", id: 12},
            {name: "中档", id: 13},
            {name: "较难", id: 14},
            {name: "难", id: 15},
        ].find((i) => i.id === v)?.name;

    export default {
        props: {
            searchParams: {
                type: Object,
                default: () => ({})
            }
        },
        components: {TestBasketComponent},
        directives: {question: QuestionDirective},
        setup(props) {
            onMounted(() => {
                emitter.on("selection-change", () => {
                    pageAorder.current = 1;
                });
                emitter.on("remove-questionBase", (data) => {
                    $.clone(cartList.value).forEach((qus: any) => {
                        if (qus.type == data) {
                            addCart(qus);
                        }
                    });
                });
                emitter.on("clear-questionBase", () => {
                    $.clone(cartList.value).forEach((qus: any) => {
                        addCart(qus);
                    });
                });
            });

            let store = useStore();
            let userId = computed(() => store.getters.userInfo.user.id);
            let dataset: Ref<any[]> = ref([]);
            let showAnswer = ref(true);
            let total = ref(0)
            let pageAorder = reactive({
                current: 1,
                size: 10,
            });
            let __params: any = {};
            let loading = ref(false);
            let wrongQuesSum = ref(0);
            let classErrorCount = ref();

            const request = async (params?, clearPage?) => {
                if (clearPage) {
                    pageAorder.current = 1
                    pageAorder.size = 10
                }
                loading.value = true;
                params && (__params = params);
                let res = await $.http.post(`/admin/lessonSummary/queryStudentWrongQuestions`, {...__params, ...pageAorder});
                if (res.result) {
                    dataset.value = res.json.records.map((n) => ({
                        ...n.questionDto,
                        ...{
                            // errorCount: n.questionCount,
                            createTime: n.createTime?.split("-").join("/").split(" ")[0],
                            difficult: difficultFilter(n.questionDto.difficult),
                            answer: n.questionDto.rightAnswer ? n.questionDto.rightAnswer.map((a, index) => {
                                if (a.hasOwnProperty('name' || a.hasOwnProperty('content'))) {
                                    if (n.questionDto.basicQuestionType !== 3) {
                                        if (n.questionDto.basicQuestionType === 1 || n.questionDto.basicQuestionType === 2) {
                                            return a["name"]
                                        } else {
                                            return a["content"]
                                        }
                                    }
                                    return `<div style="display:flex">（${index + 1}）${a[n.questionDto.basicQuestionType === 1 || n.questionDto.basicQuestionType === 2 ? "name" : "content"]}</div>`;
                                } else {
                                    return '暂无答案'
                                }
                            }).join('、') : '暂无答案',
                        },
                    }));
                    total.value = res.json.total;
                    wrongQuesSum.value = res.json.total
                }

                loading.value = false;
                nextTick(() => {
                    let container = document.querySelector('.section-main');
                    container && (container.scrollTop = 0);
                });
            };

            $.emitter.on('question-request', () => request(props.searchParams))

            let cartList: Ref<any[]> = ref($.storage.get('cartListValue') || []);

            const addCart = (data) => {
                let index = cartList.value.findIndex(d => d.id === data.id);
                index > -1 ? cartList.value.splice(index, 1) : cartList.value.push(data);
                $.storage.set('cartListValue', cartList.value);
            };

            const filterKnowle = (data) => {
                if (!data.knowledges) {
                    return;
                }
                return data.knowledges.map(ele => ele.name).join(',');
            };

            return {
                request, loading, dataset, pageAorder, showAnswer, userId,
                cartList, addCart, filterKnowle, wrongQuesSum, classErrorCount, total, rewriteRichPic: function (richText) {
                    return richText.replace(new RegExp("(i?)(\<img.*?style=['\"])([^\>]+\>)", 'gmi'), '$2max-width:100%;height:auto;$3')
                }
            }
        },
    };
</script>

<style lang="scss" scoped>
    .container {
        flex: auto;
        display: flex;
        flex-direction: column;
        margin-top: 15px;
        height: 100%;

        & > .fixed-header {
            padding: 0 28px;
            color: #fff;
            line-height: 34px;
            background: #72b22a;
            border-radius: 6px 6px 0px 0px;

            .wrong-list {
                & > :nth-child(1) {
                    font-size: 16px;
                    margin-right: 4px;
                }

                & > :nth-child(2) {
                    i {
                        color: #faad14;
                    }
                }
            }
        }

        .section {
            flex: 1 1 36px;
            background: #fff;
            padding: 20px 28px;

            .item {
                padding: 20px 20px 0;
                border-radius: 10px;
                border: 1px solid #ebeef6;
                position: relative;
                transition: all 0.25s;

                &.is__selected {
                    cursor: pointer;
                }

                &.is__disabled {
                    pointer-events: none;
                    background: #f9f9f9;
                }

                &.is__checked {
                    border-color: #19aea5;
                }

                &:not(:last-child) {
                    margin-bottom: 20px;
                }

                &:hover {
                    box-shadow: 0px 2px 11px 0px rgba(23, 18, 45, 0.2);
                }

                .title {
                    margin-bottom: 20px;
                }

                .content-text {
                    margin-right: 20px;
                    overflow: hidden;

                    img {
                        display: inline-block;
                    }
                }

                .flex-box {
                    font-size: 13px;
                    display: flex;
                    margin-top: 14px;

                    .label {
                        display: inline-block;
                        height: 20px;
                        padding: 0 7px;
                        color: #3abab3;
                        font-size: 12px;
                        line-height: 20px;
                        background: rgba(58, 186, 179, 0.15);
                        border-radius: 4px;
                        margin-right: 8px;
                        width: 50px;
                        white-space: nowrap;
                    }

                    .flex-main {
                        flex: auto;
                        color: #77808d;
                    }
                }

                .footer {
                    height: 36px;
                    margin: 20px -20px 0;
                    font-size: 12px;
                    line-height: 36px;
                    background: #f2f1f6;
                    border-bottom-left-radius: 8px;
                    border-bottom-right-radius: 8px;
                    border-top: solid 1px #ebf0fc;

                    .error-btn {
                        margin-left: 10px;
                        color: $--color-danger;
                        border-color: $--color-danger;
                        background: #FFEFEB;
                    }

                    .footer-source {
                        width: calc(100vw - 1200px);
                        padding: 0;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }

                    p {
                        float: left;
                        margin-left: 18px;
                        color: #1a2633;

                        span {
                            color: #77808d;
                        }

                        i {
                            color: #382a74;
                            cursor: pointer;

                            &:active {
                                opacity: 0.6;
                            }
                        }
                    }

                    div {
                        float: right;
                        padding-right: 20px;

                        a {
                            display: inline-block;
                            padding: 0 10px;
                            margin-left: 20px;
                            color: #72b22a;
                            line-height: 20px;
                            border: solid 1px #72b22a;
                            border-radius: 12px;
                            transition: all 0.25s;
                            cursor: pointer;

                            &.is__loading {
                                pointer-events: none;
                                opacity: 0.6;
                            }

                            &.cart-icon.active {
                                color: #faad14;
                                border: solid 1px #faad14;
                                background: #fff7e9;

                                &::before {
                                    content: "移出试题篮";
                                }
                            }

                            &.cart-icon::before {
                                content: "加入试题篮";
                                display: inline-block;
                            }
                        }

                        & > i {
                            color: #5b7dff;
                            font-size: 18px;
                            line-height: 36px;
                            margin-right: 20px;
                            vertical-align: top;
                            cursor: pointer;

                            &:active {
                                opacity: 0.8;
                            }
                        }
                    }
                }
            }
        }

        :deep(.el-pagination) {
            text-align: right;
        }
    }

    :deep(.item) {
        .e-main {
            display: flex;
            flex-wrap: wrap;
            padding-left: 20px;

            .e-m-cell {
                display: flex;
                align-items: center;

                > img {
                    margin-left: 5px;
                }

                &.w-1 {
                    width: 100%;
                }

                &.w-2 {
                    width: 50%;
                }

                &.w-4 {
                    width: 25%;
                }

                margin-bottom: 10px;

                .e-c-label {
                    width: 40px;
                }

                .e-c-group {
                    flex: 1 1 40px;
                    display: flex;
                    flex-wrap: wrap;

                    .c-t-item {
                        flex: 1;
                        white-space: nowrap;
                    }
                }
            }

            &-title {
                .e-m-cell {
                    margin-bottom: 20px;

                    .e-c-label {
                        margin-bottom: 5px;
                    }

                    .e-c-group {
                        line-height: 24px;
                        text-indent: 20px;
                    }
                }
            }
        }
    }

    :deep(.el-button--mini) {
        min-height: 22px;
    }

    :deep(.el-button--mini.is-round) {
        padding: 2px 10px;
    }
</style>
